<?php
namespace Illuminate\Foundation\Support\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Router;
use Illuminate\Contracts\Routing\UrlGenerator;

class RouteServiceProvider extends ServiceProvider {
    protected $namespace;

    public function boot() {
        $this->setRootControllerNamespace();

        if ( $this->app->routesAreCached() ) { // 路由已缓存
            $this->loadCachedRoutes(); // 加载已缓存的路由
        } else {
            $this->loadRoutes(); // 加载路由

            $this->app->booted(function () {
                $this->app['router']->getRoutes()->refreshNameLookups();
                $this->app['router']->getRoutes()->refreshActionLookups();
            });
        }
    }

    protected function setRootControllerNamespace() { // 设置根控制器命名空间
        if ( ! is_null($this->namespace) ) {
            $this->app[UrlGenerator::class]->setRootControllerNamespace($this->namespace);
        }
    }
    protected function loadCachedRoutes() { // 加载已缓存路由
        $this->app->booted(function () {
            require $this->app->getCachedRoutesPath(); // 路径
        });
    }
    protected function loadRoutes() { // 加载路由
        if ( method_exists($this, 'map') ) $this->app->call([$this, 'map']);
    }
    public function register() {}

    public function __call($method, $parameters) {
        return call_user_func_array(
            [$this->app->make(Router::class), $method], $parameters
        );
    }
}
